/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hessingerbg.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;

public class Splash extends Window {
  private Image splashImage;
  private int imgWidth, imgHeight;
  private String imgName;
  private static final int BORDERSIZE = 5;
  private static final Color BORDERCOLOR = Color.blue;
  JFrame f;
  Toolkit tk;

  /**
   * Constructor Splash: Loads a splash screen in which it waits for the frame
   * passed to become visible.
   * @param f The frame we should wait for the load event
   * @param imgName The image we want to use as the splash screen
   */
  public Splash(JFrame f, String imgName) {
    super(f);
    f = f;
    this.imgName = imgName;
    tk = Toolkit.getDefaultToolkit();

    splashImage = loadSplashImage();
    showSplashScreen();
    f.addWindowListener(new WindowListener());

    }

  private Image loadSplashImage() {
    MediaTracker tracker = new MediaTracker(this);
    Image result;
    result = tk.createImage(imgName);

    tracker.addImage(result, 0);
    try
    {
      tracker.waitForAll();
    }
    catch (Exception e) {
      e.printStackTrace();
      }
    imgWidth = result.getWidth(this);
    imgHeight = result.getHeight(this);
    return (result);
    }

  private void showSplashScreen() {
    Dimension screenSize = tk.getScreenSize();
    setBackground(BORDERCOLOR);
    int w = imgWidth + (BORDERSIZE * 2);
    int h = imgHeight + (BORDERSIZE * 2);
    int x = (screenSize.width - w) /2;
    int y = (screenSize.height - h) /2;
    setBounds(x, y, w, h);
    setVisible(true);
    }

    @Override
  public void paint(Graphics g) {
    g.drawImage(splashImage, BORDERSIZE, BORDERSIZE,
      imgWidth, imgHeight, this);
    }

  class WindowListener extends WindowAdapter {
    //  was windowActivated, thanks to H.Grippa for the fix!
        @Override
    public void windowClosed(WindowEvent we) {

      setVisible(false);
      dispose();
      }
    }


}
